package com.fausto.learnimprint.core.controller.impl

import cn.hutool.core.util.StrUtil
import com.fausto.learnimprint.core.model.dto.CommonResult
import com.fausto.learnimprint.core.service.ITagService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.*

/**
 *
 *
 * 前端控制器
 *
 *
 * @author fausto
 * @since 2022-03-28
 */
@Api(tags = ["标签API"], basePath = "/tags")
@RestController
@RequestMapping("/tags")
class TagController {

    @Autowired
    lateinit var tagService: ITagService

    /**
     *  添加标签
     */
    @ApiOperation(value = "新增标签")
    @PreAuthorize("hasAuthority('USER')")
    @PostMapping
    fun newTag(
        @ApiParam(value = "标签名", required = true, example = "新标签")
        tagName: String
    ): CommonResult<Any>{
        return if (StrUtil.isBlank(tagName)){
            CommonResult.fail("参数错误")
        }else try {
            tagService.save(tagName)
            CommonResult.ok("添加标签成功")
        } catch (e: RuntimeException){
            CommonResult.fail("操作失败", data = e.message)
        }
    }

    /**
     *  获取某个用户下的所有标签
     */
    @ApiOperation(value = "获取用户标签")
    @PreAuthorize("hasAuthority('USER')")
    @GetMapping
    fun findTagByUserId(): CommonResult<Any>{
        return try {
            CommonResult.ok("获取标签成功", data = tagService.findTagByUserId())
        } catch (e: RuntimeException){
            CommonResult.fail("操作失败", data = e.message)
        }
    }

    /**
     *      修改一个标签
     */
    @ApiOperation(value = "修改标签")
    @PreAuthorize("hasAuthority('USER')")
    @PutMapping
    fun updateTag(
        @ApiParam(value = "标签ID", required = true, example = "1")
        tagId: Int,
        @ApiParam(value = "新标签名", required = true, example = "默认标签")
        tagName: String
    ): CommonResult<Any>{
        return if (StrUtil.isBlank(tagName)){
            CommonResult.fail("标签名不能为空")
        }else try {
            tagService.updateTag(tagId, tagName)
            CommonResult.ok("修改标签成功")
        } catch (e: RuntimeException){
            CommonResult.fail("操作失败", data = e.message)
        }
    }

    /**
     *      删除标签
     */
    @ApiOperation(value = "删除标签")
    @PreAuthorize("hasAuthority('USER')")
    @DeleteMapping("/{tagId}")
    fun deleteTag(
        @ApiParam(value = "标签ID", required = true, example = "1")
        @PathVariable
        tagId: Int
    ): CommonResult<Any>{
        return try {
            tagService.deleteTag(tagId)
            CommonResult.ok("删除标签成功")
        } catch (e: RuntimeException){
            CommonResult.fail("操作失败", data = e.message)
        }
    }
}